﻿using LineFocus.Nikcron.Common;
using LineFocus.Nikcron.Models;
using Nickron.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LineFocus.Nikcron.Controllers
{
    public class SalesController : BaseController
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetSales() {
            ApplicationDBContext db = new ApplicationDBContext();
            JsonResult result = new JsonResult();
            var Sales = from s in db.WholeSales.ToList()
                        select new
                        {
                            InvoiceId = s.Id,
                            InvoiceDate = s.InvoiceDate.Value.ToShortDateString(),
                            InvoiceNumber = s.InvoiceNumber,
                            Stockhouse = s.Stockhouse.Name,
                            Retailer = s.Retailer.Name,
                            Status = s.InvoiceStatus,
                            Products = new
                            {
                                Product = s.ProductItems.Select(p => p.ProductModel.Manufacture.Name + " - " + p.ProductModel.ModelNumber + "(" + p.IMEI1 + ")"),
                                Qty = s.ProductItems.Select(p => 1),
                                UnitPrice = s.ProductItems.Select(p => p.UnitPrice.Amount),
                                LineTotal = s.ProductItems.Select(p => p.UnitPrice.Amount)
                            },
                            Accessories = new { 
                                Product = s.Accessories.Select(a=>a.Accessory.Manufacture.Name + " - " + a.Accessory.ModelName),
                                Qty = s.Accessories.Select(a=>a.Qty),
                                UnitPrice = s.Accessories.Select(a=>a.UnitPrice.Amount),
                                LineTotal = s.Accessories.Select(a=>a.UnitPrice.Amount * a.Qty)
                            },
                            TotalQtys = s.ProductItems.Count + s.Accessories.Sum(a=>a.Qty),
                            TotalAmt = s.ProductItems.Sum(p=>p.UnitPrice.Amount) + s.Accessories.Sum(a=>a.TotalPrice.Amount)
                        };
            result.Data = Sales;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        [HttpGet]
        public JsonResult GetProductItemDetailsForSales(string IMEINo, int? IsRetailSale)
        {
            ApplicationDBContext db = new ApplicationDBContext();
            JsonResult result = new JsonResult();
            var Sales = from p in db.ProductItems
                        where p.IMEI1 == IMEINo && ((!IsRetailSale.HasValue && p.WholeSaleId == null) || (IsRetailSale.HasValue && p.WholeSaleId != null))
                        select new
                        {
                            ItemId = p.Id,
                            Brand = p.ProductModel.Manufacture.Name,
                            Model = p.ProductModel.ModelNumber,
                            IMEI1 = p.IMEI1,
                            IMEI2 = p.IMEI2,
                            SerialNo = p.SerialNumber,
                            UnitPrice = p.UnitPrice.Amount,
                            Qty = 1,
                            LineTotal = p.UnitPrice.Amount
                        };
            result.Data = Sales;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        [HttpGet]
        public JsonResult GetItemDetailsForSalesId(int? SalesId)
        {
            ApplicationDBContext db = new ApplicationDBContext();
            JsonResult result = new JsonResult();
            var Sales = db.WholeSales.Where(s=>s.Id == SalesId).FirstOrDefault();
            var Items = from p in Sales.ProductItems
                        select new { 
                            Brand = p.ProductModel.Manufacture.Name,
                            Model = p.ProductModel.ModelNumber,
                            IMEI1 = p.IMEI1,
                            IMEI2 = p.IMEI2,
                            SerialNo = p.SerialNumber
                        };
            result.Data = Items;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        [HttpGet]
        public ActionResult Maintenance()
        {
            Lookup Lookup_Stockhouses = new Lookup();
            Lookup Lookup_Retailers = new Lookup();
            Lookup Lookup_Brands = new Lookup();
            Lookup Lookup_AccessoryModels = new Lookup();

            ApplicationDBContext db = new ApplicationDBContext();

            var query5 = from records in db.Offices.OfType<Stockhouse>().ToList().Where(s => s.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name};
            Lookup_Stockhouses.Items = query5.ToList();

            var query6 = from records in db.Offices.OfType<Retailer>().ToList().Where(s => s.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name, ParentId = records.Dealer.Distributor.StockhouseId };
            Lookup_Retailers.Parent = "Stockhouse";
            Lookup_Retailers.Items = query6.ToList();

            var query7 = from records in db.Manufactures.ToList()
                         select new LookupItem() { Id = records.Id, Name = records.Name };
            Lookup_Brands.Items = query7.ToList();

            var query8 = from records in db.ProductModels.Where(m => m.ProductType.Name == "Accessory")
                         select new LookupItem() { Id = records.Id, Name = records.ModelName, ParentId = records.ManufactureId };
            Lookup_AccessoryModels.Parent = "Manufacture";
            Lookup_AccessoryModels.Items = query8.ToList();

            ViewBag.Stockhouses = Lookup_Stockhouses;
            ViewBag.Retailers = Lookup_Retailers;
            ViewBag.Brands = Lookup_Brands;
            ViewBag.Accessories = Lookup_AccessoryModels;
            return View();
        }

        [HttpPost]
        public ActionResult Maintenance(FormCollection formCollection)
        {
            ApplicationDBContext db = new ApplicationDBContext();
            WholeSale Sale = new WholeSale();
            Parameters TransitNumber = db.Parameters.Where(p => p.Id == (int)ParameterTypes.Transit).FirstOrDefault();
            Sale.InvoiceNumber = TransitNumber.Number;
            Sale.StockhouseId = Int32.Parse(formCollection["Stockhouse"]);
            Sale.RetailerId = Int32.Parse(formCollection["Retailer"]);
            Sale.InvoiceDate = DateTime.Parse(formCollection["InvoiceDate"]);
            Sale.InvoiceStatus = StockStatus.InHouse.ToString();
            TransitNumber.Number++;

            string[] ModelNos = formCollection["ModelNos"].Split(new char[] { ',' }).ToArray();
            string[] IMEIs = formCollection["IMEIs"].Split(new char[] { ',' }).ToArray();
            string[] Qtys = formCollection["Qtys"].Split(new char[] { ',' }).ToArray();
            string[] UnitPrices = formCollection["UnitPrices"].Split(new char[] { ',' }).ToArray();

            for (int i = 0; i < ModelNos.Length; i++)
            {
                if (string.IsNullOrEmpty(IMEIs[i]))
                {
                    WholeSaleAccessory accessory = new WholeSaleAccessory();
                    accessory.AccessoryId = int.Parse(ModelNos[i]) * -1;
                    accessory.Qty = int.Parse(Qtys[i]);
                    accessory.UnitPrice.Currency = Currencies.INR.ToString();
                    accessory.UnitPrice.Amount = double.Parse(UnitPrices[i]);
                    accessory.TotalPrice.Currency = Currencies.INR.ToString();
                    accessory.TotalPrice.Amount = accessory.UnitPrice.Amount.Value * accessory.Qty;
                    db.WholeSaleAccessories.AddObject(accessory);
                    Sale.Accessories.Add(accessory);
                }
                else
                { 
                    int ItemId = int.Parse(ModelNos[i]);
                    ProductItem Product = db.ProductItems.Where(p => p.Id == ItemId).FirstOrDefault();
                    Product.UnitPrice.Amount = double.Parse(UnitPrices[i]);
                    Sale.ProductItems.Add(Product);
                }
                
            }
            Sale.InvoiceAmount.Currency = Currencies.INR.ToString();
            Sale.InvoiceAmount.Amount = Sale.Accessories.Sum(a => a.TotalPrice.Amount) + Sale.ProductItems.Sum(p => p.UnitPrice.Amount);
            Sale.TransitStatus = StockStatus.InHouse.ToString();
            Sale.Status.IsActive = true;

            db.WholeSales.AddObject(Sale);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult RetailSales()
        {
            Lookup Lookup_Retailers = new Lookup();
            Lookup Lookup_States = new Lookup();
            Lookup Lookup_Countries = new Lookup();

            ApplicationDBContext db = new ApplicationDBContext();
            
            var query6 = from records in db.Offices.OfType<Retailer>().ToList().Where(s => s.Status.IsDeleted != true)
                         select new LookupItem() { Id = records.Id, Name = records.Name };
            Lookup_Retailers.Items = query6.ToList();

            var query7 = from records in db.Countries.ToList()
                         select new LookupItem() { Id = records.Id, Name = records.Name };
            Lookup_Countries.Items = query7.ToList();

            var query8 = from records in db.States.ToList()
                         select new LookupItem() { Id = records.Id, Name = records.Name, ParentId = records.CountryId };
            Lookup_States.Parent = "Country";
            Lookup_States.Items = query8.ToList();

            ViewBag.Retailers = Lookup_Retailers;
            ViewBag.States = Lookup_States;
            ViewBag.Countries = Lookup_Countries;
            return View();
        }

        [HttpPost]
        public ActionResult RetailSales(FormCollection formCollection)
        {
            ApplicationDBContext db = new ApplicationDBContext();
            Customer NewCustomer = new Customer();
            NewCustomer.FirstName = formCollection["FirstName"];
            NewCustomer.LastName = formCollection["LastName"];
            NewCustomer.PresentAddress.Address1 = formCollection["Address1"];
            NewCustomer.PresentAddress.Address2 = formCollection["Address2"];
            NewCustomer.PresentAddress.City = formCollection["City"];
            NewCustomer.PresentAddress.State = formCollection["State"];
            NewCustomer.PresentAddress.Country = formCollection["Country"];
            NewCustomer.PresentAddress.Zip = formCollection["Zip"];
            //NewCustomer.PermanentAddress = NewCustomer.PresentAddress;
            NewCustomer.Contact.Mobile = formCollection["Mobile"];
            NewCustomer.Contact.Phone = formCollection["Phone"];
            NewCustomer.Contact.Email = formCollection["Email"];
            db.People.AddObject(NewCustomer);
            db.SaveChanges();

            Sale RetailSale = new Sale();
            int ProductItemId = Int32.Parse(formCollection["ProductItemId"]);
            ProductItem ProductItem = db.ProductItems.Where(p=>p.Id == ProductItemId).FirstOrDefault();
            Parameters InvoiceNumber = db.Parameters.Where(p => p.Id == (int)ParameterTypes.Invoice).FirstOrDefault();
            RetailSale.InvoiceNumber = InvoiceNumber.Number.ToString();
            RetailSale.ProductItemId = ProductItemId;
            RetailSale.InvoicedDate = DateTime.Parse(formCollection["SellingDate"]);
            RetailSale.WarrantyStart = DateTime.Parse(formCollection["DOS"]);
            RetailSale.WarrantyEnd = DateTime.Parse(formCollection["DOE"]);
            RetailSale.ProductCost.Currency = ProductItem.SellingPrice.Currency;
            RetailSale.ProductCost.Amount = ProductItem.SellingPrice.Amount;
            RetailSale.Paid.Currency = Currencies.INR.ToString();
            RetailSale.Paid.Amount = Double.Parse(formCollection["SellingPrice"]);
            RetailSale.Discount.Currency = Currencies.INR.ToString();
            RetailSale.Discount.Amount = ProductItem.SellingPrice.Amount - Double.Parse(formCollection["SellingPrice"]);
            RetailSale.UserId = this.User.UserId;
            RetailSale.CustomerId = NewCustomer.Id;
            db.Sales.AddObject(RetailSale);
            db.SaveChanges();
            return View();
        }

    }
}
